package com.janchow.whisper.server.chat.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerOptions;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by Jange on 2016/5/24.
 */
public class ChatVerticle extends AbstractVerticle {
    private Vertx vertx;

    @Override
    public void init(Vertx vertx, Context context) {
        this.vertx = vertx;
    }

    @Override
    public void start() throws Exception {
        HttpServerOptions options = new HttpServerOptions().setPort(54009);
        vertx.createHttpServer(options).websocketHandler(res -> {
            String clientID = res.textHandlerID();      //UUID
            //处理客户端的消息


            res.handler(buffer -> {
                System.out.println(buffer);

                System.out.println(buffer);
                if (StringUtils.isEmpty(buffer.toString())) {
                    this.sendBus(clientID, "unknown command!");
                    return;
                }
            });

            res.closeHandler(h -> {
                System.out.println("websocket handler has been closed!");
            });

            res.exceptionHandler(h -> {
                h.printStackTrace();
                System.out.println("websocket handler ouccer an exception :" + h.getMessage());
            });

            res.endHandler(h -> {
                System.out.println("websocket handler handle data end!");
            });

            //客户端连接上来后的操作

//            addClient(client);

            //发送消息给客户端

            sendBus(clientID, "yesman");
        });
    }

    @Override
    public void stop() throws Exception {
        super.stop();
    }

    public void sendBus(String address, Object data) {
        vertx.eventBus().send(address, data);
    }

}
